<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=8">
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title></title>

    <script type="text/javascript">
        var objApp = window.external;
        try {
            var objCommon = objApp.CreateWizObject("WizKMControls.WizCommonUI");
            //
            window.UEDITOR_HOME_URL = objApp.GetPluginPathByScriptFileName("wiz_ueditor.js").replace(/\\/gi, "/");
        }
        catch (err) {
        }
    </script>

    <!-- ueditor -->
    <script type="text/javascript" charset="utf-8" src="ueditor.config.js"></script>
    <script type="text/javascript" charset="utf-8" src="ueditor.all.js"></script>
    <script type="text/javascript" charset="utf-8" src="lang/zh-cn/zh-cn.js"></script>

    <!-- KityFormula 插件需要加载的js -->
    <script type="text/javascript" charset="utf-8" src="third-party/kityformula-plugin/addKityFormulaDialog.js"></script>
    <script type="text/javascript" charset="utf-8" src="third-party/kityformula-plugin/getKfContent.js"></script>
    <script type="text/javascript" charset="utf-8" src="third-party/kityformula-plugin/defaultFilterFix.js"></script>

    <!-- KityMinder 插件需要加载的js -->
    <!-- <script type="text/javascript" charset="utf-8" src="third-party/kityminder-plugin/addkityMinderDialog.js"></script>-->
	
	<!-- grapheditor 插件需要加载的js -->
    <script type="text/javascript" charset="utf-8" src="third-party/grapheditor-plugin/addGraphEditorDialog.js"></script>

    <script type="text/javascript" charset="utf-8" src="third-party/SyntaxHighlighter/shCore.js"></script>
    <style type="text/css">
        .edui-for-mybutton .edui-icon
        {
            background-position: -480px -20px;
        }
    </style>
</head>
<body>
    <div id="presavewiz" style="display:none;"></div>
    <textarea id="textareaEditor" cols="1"></textarea>

    <script type="text/javascript">
        //
        function loadString(name) {
            if (objDocument) {
                var languageFileName = getPluginPath() + "plugin.ini";
                return objApp.LoadStringFromFile(languageFileName, name);
            }
            return name;
        }
        //
        function getQueryString(name) {
            if (location.href.indexOf("?") == -1 || location.href.indexOf(name + '=') == -1) {
                return '';
            }
            var queryString = location.href.substring(location.href.indexOf("?") + 1);

            var parameters = queryString.split("&");

            var pos, paraName, paraValue;
            for (var i = 0; i < parameters.length; i++) {
                pos = parameters[i].indexOf('=');
                if (pos == -1) { continue; }

                paraName = parameters[i].substring(0, pos);
                paraValue = parameters[i].substring(pos + 1);

                if (paraName == name) {
                    return unescape(paraValue.replace(/\+/g, " "));
                }
            }
            return '';
        };

        //
        var guid = getQueryString("guid");
        var kbGUID = getQueryString("kbguid");
        //
        var objDatabase = null;
        if (kbGUID == "" || kbGUID == null) {
            objDatabase = objApp.Database;
        }
        else {
            objDatabase = objApp.GetGroupDatabase(kbGUID);
        }
        //
        var objDocument = null;
        //
        try {
            objDocument = objDatabase.DocumentFromGUID(guid);
        }
        catch (err) {
        }

        //
        var modified = false;
        var editor = null;
        //
        {
            var htmlText = "";
            if (objDocument) {
                // 防止md笔记出错
                document.title = "编辑 " + objDocument.Title.replace(new RegExp(".md", "gi"), "");

                var tempPath = objCommon.GetSpecialFolder("TemporaryFolder");
                tempPath += "ueditor_temp/";
                objCommon.CreateDirectory(tempPath);
                tempPath += objDocument.GUID + "/";
                objCommon.CreateDirectory(tempPath);

                var tempFileName = objDocument.GUID;
                var tempFileDir = tempFileName + "_files";
                objCommon.CreateDirectory(tempPath + tempFileDir + "/");

                var tempFile = tempPath + tempFileName + ".html";
                objDocument.SaveToHtml(tempFile, 0);
                htmlText = objCommon.LoadTextFromFile(tempFile);

                var replaceFrom = new RegExp(tempFileDir, "gi");
                var tempFileDirAbsolute = tempPath + tempFileDir;
                htmlText = htmlText.replace(replaceFrom, tempFileDirAbsolute);
            }

            var options = {
                editorFullHtml: htmlText
            };

            editor = UE.getEditor('textareaEditor', options);

            UE.registerUI('button', function(editor, uiName){
                var strSave = loadString("Save");
                var saveButton = new UE.ui.Button({
                    className: 'edui-for-mybutton',
                    title: strSave,
                    label: strSave,
                    showText: false,
                    onclick: function() {
                        saveDocument(editor);
                    }
                });
                return saveButton;
            }, 0);

            //
            function onAfterExecCommand() {
                modified = true;
            }
            //
            function onKeyDown(type, evt) {
                modified = true;
                var e = evt;
                if (e.ctrlKey && !e.altKey && !e.shiftKey) {
                    if (String.fromCharCode(e.keyCode).toLocaleUpperCase() == 'S') {

                        saveDocument(editor);
                        //
                        e.returnValue = false;
                    }
                    else if (String.fromCharCode(e.keyCode).toLocaleUpperCase() == 'V') {
                        if (actionPaste()) {
                            e.returnValue = false;
                            e.keyCode = 0;
                        }
                        else {
                        }
                    }
                }
                else if (!e.ctrlKey && !e.altKey && !e.shiftKey && e.keyCode == 112) { // F1
                    editor.execCommand("inserthtml", "&nbsp;&nbsp;&nbsp;&nbsp;");
                }
            }

            function onImageUploadLocal() {
                var filename = objCommon.SelectWindowsFile(true, "Image Files(*.png;*.jpg;*.gif;*.bmp)|*.png;*.jpg;*.gif;*.bmp|");
                return filename;
            }

            function onCaptureScreenImage() {
                var filename = objCommon.CaptureScreen(0);
                if (!objCommon.PathFileExists(filename)) {
                    filename = "";
                }
                return filename;
            }

            function onSaveCanvasImage(type, strText) {
                var filename = objCommon.GetATempFileName(".png");
                try {
                    objCommon.SaveTextToFile(filename, strText, "ansi");
                }
                catch (err) {
                    alert(err);
                    return "";
                }
                return filename;
            }
            //
            editor.addListener('afterexeccommand', onAfterExecCommand);
            editor.addListener('keydown', onKeyDown);
            editor.addListener('imgUploadLocalDown', onImageUploadLocal);
            editor.addListener('captureScreenImage', onCaptureScreenImage);
            editor.addListener('saveCanvasImageWiz', onSaveCanvasImage);
        }

        function actionPaste() {
            try {
                var imagefilename = objCommon.ClipboardToImage(objApp.Window.HWND, "");
                if (!imagefilename)
                    return false;
                //
                var html = "<img border=\"0\" src=\"" + imagefilename + "\" />";
                editor.execCommand("inserthtml", html);
                return true;
            }
            catch (err) {
                return false;
            }
        }

        //缓存前一次保存的，解决为知4.5版本自动保存问题
        var wizVerisonGreaterThan45 = null;
        var savePreHtml = null;
        var savePreTime = null;
        try {
            wizVerisonGreaterThan45 = objApp.Window.CurrentDocumentBrowserObject != null;
        }
        catch (err) {
        }

        function saveDocument(editor) {
            var fullHtml = getEditorHtml();
            objDocument.UpdateDocument3(fullHtml, 0);
            modified = false;
        }
        function OnPluginQueryModified() {
            var modifiedTemp = modified;
            modified = false; // 防止再次调用window.onbeforeunload
            return modifiedTemp;
        }
        function OnPluginSave() {
            if (wizVerisonGreaterThan45) {
                savePreHtml = null;
                if (modified) {
                    savePreHtml = objDocument.GetHtml();
                    saveDocument(editor);
                    savePreTime = new Date();
                }
            }
            else {
                saveDocument(editor);
            }

            return true;
        }
        function getPluginPath() {
            var pluginPath = "";
            try {
                pluginPath = objApp.GetPluginPathByScriptFileName("wiz_ueditor.js");
            }
            catch (err) {
            }
            return pluginPath;
        }

        // 保存时处理高亮
        function getEditorHtml () {
            var fullHtml = editor.getAllHtml();
            fullHtml = "<!DOCTYPE html>" + fullHtml;

            if (fullHtml.indexOf('<pre class="brush') == -1) {
                return fullHtml;
            }

            var preElem = document.getElementById("presavewiz");
            if (!preElem) {
                return fullHtml;
            }

            var content = editor.getContent();
            preElem.innerHTML = content;

            var pres = preElem.getElementsByTagName('pre');
            if(pres.length){
                for (var i = 0; i < pres.length; i++) {
                    var pi = pres[i];
                    if(pi && /brush/i.test(pi.className)){
                        SyntaxHighlighter.highlight(pi);
                    }
                }
            }

            content = preElem.innerHTML;
            preElem.innerHTML = "";

            var startBody = fullHtml.indexOf('<body');
            var headHtml = fullHtml.substring(0, startBody);

            if (headHtml.indexOf('/shCoreDefault') == -1) {
                var addHtml = '<link rel="stylesheet" type="text/css" href="' +
                    getPluginPath() + 'third-party/SyntaxHighlighter/shCoreDefault.css"/>';

                var endHead = headHtml.indexOf('</head>');
                headHtml = headHtml.substring(0, endHead) + addHtml + headHtml.substring(endHead);
            }

            fullHtml = headHtml + '<body ' + (UE.browser.ie && UE.browser.version < 9 ? 'class="view"' : '') + '>' + content + '</body></html>';

            return fullHtml;
        }

        ////////////////////////////////////////////////
        // 预防页面被跳转丢失编辑
        window.onbeforeunload = function () {
            if (modified) {
                modified = false;
                if (6 == objApp.Window.ShowMessage("是否将更改保存到 " + objDocument.Title + " ？", "{p}", 0x04 + 0x20)) {
                    saveDocument();
                }
            }
        }

        ////////////////////////////////////////////////
        // 关闭标签前的事件
        function onBeforeCloseTab_WizUEditor() {
            if (wizVerisonGreaterThan45 && savePreHtml && savePreTime) {
                var closeTime = new Date();
                var spanTime = closeTime.getTime() - savePreTime.getTime();
                if (spanTime < 800) { // 间隔太短表示自动保存了
                    if (6 != objApp.Window.ShowMessage("是否将更改保存到 " + objDocument.Title + " ？", "{p}", 0x04 + 0x20)) {
                        objDocument.UpdateDocument3(savePreHtml, 0);
                    }
                }
            }
        }
    </script>

</body>
</html>
